package com.mazaiting;

import cn.hutool.core.util.ObjectUtil;
import com.mazaiting.classpath.ClassResponse;
import com.mazaiting.classpath.Classpath;
import lombok.extern.slf4j.Slf4j;

/**
 * 应用启动类
 * 测试参数:
 * -Xjre "/Library/Java/JavaVirtualMachines/jdk1.8.0_291.jdk/Contents/Home/jre" java.lang.Object
 *
 * @author mazaiting
 * @since 2021/8/10
 */
@Slf4j
public class SJava {
    public static void main(String[] args) {

        Cmd cmd = Cmd.parseCmd(args);
        if (cmd.isVersionFlag()) {
            System.out.println("version 0.0.1");
        } else if (cmd.isHelpFlag()) {
            log.info("Usage: {} [-options] class [args...]", SJava.class.getSimpleName());
        } else {
            startJVM(cmd);
        }
    }

    /**
     * 启动 JVM
     *
     * @param cmd 命令行参数
     */
    private static void startJVM(Cmd cmd) {
        // 解析
        Classpath classpath = new Classpath(cmd.getXjreOption(), cmd.getCpOption());
        log.info("classpath:{} class:{} args:{}\n", classpath, cmd.getClassName(), cmd.getArgs());
        // 替换类中的 .
        String className = cmd.getClassName().replace(".", "/");
        // 读取类
        ClassResponse classResponse = classpath.readClass(className);
        if (ObjectUtil.isNotEmpty(classResponse.getError())) {
            log.error("Could not find or load main class {}\n", cmd.getClassName());
            return;
        }
        log.info("class data:{}\n", classResponse.getBytes());
    }
}


















